//
//  SXOauthController.swift
//  微博09项目
//
//  Created by mac on 15/9/2.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD//导入设置进度条的三方框架，
class SXOauthController: UIViewController,UIWebViewDelegate {

  private var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let network = NetworkTools.shareTools.oauthUrl
       
        webView.loadRequest(NSURLRequest(URL: network))
        
    }
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "登陆新浪微博"
        view.backgroundColor = UIColor.orangeColor()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action:"backClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "AutoFill")
    }
    //移除控制器
   @objc private func backClick(){
    //点击关闭按钮的时候移除SVProgressHUD进度条
        SVProgressHUD.dismiss()
       dismissViewControllerAnimated(true, completion: nil)
        
    }
    //自动填充密码
    @objc private func AutoFill(){
        
        let js = "document.getElementById('userId').value = '18201305609';" +
        "document.getElementById('passwd').value = 'yinger1314520';"
        
        //执行js脚本
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       
        let urlString = request.URL!.absoluteString
        //1,判断前半部分是不是回调地址，如果不是继续加载
        if !urlString.hasPrefix(NetworkTools.shareTools.redirectUri) {
            //继续加载
            return true
        }
       
        print(request.URL?.query)
        //2,如果是回调地址，检查query，查询字符串，判断是否包含“code=”
        if let query = request.URL?.query where query.hasPrefix("code="){
            //3，如果有获得code
            let code = query.substringFromIndex("code=".endIndex)
           // print(code)
            
            //4，调用网络方法获取token
           UserAccountViewModel.shareUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
            printLog(error)
            }, completed: { () -> Void in
                print("登陆完成")
                SVProgressHUD.dismiss()
                //动画完成之后，再做切换根视图控制器的操作能够保证视图控制器被完全销毁
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    // 通知是同步的，动画完成之后，发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(SXSwitchRootViewControllerNotification, object: "Main")
                })
           })
            
        }else{
            print("取消")
        }
       // print("vebview + \(webView)")
        return false
    }
    //展示进度条
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
      
    }
    //移除进度条
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
       
    }
  
}
